package httpcommon

import (
	"net/http"
	"strings"

	lg "gitee.com/bm_guangge/bm_common/log"
)

func removePort(addr string) string {
	index := strings.LastIndex(addr, ":")
	ip := addr[:index]
	return ip
}

// 获取请求中的IP
func RemoteIp(req *http.Request) string {
	var remoteAddr string
	// X-Real-Ip
	remoteAddr = req.Header.Get("X-Real-Ip")
	if remoteAddr != "" {
		lg.ILogger.Println("X-Real-Ip")
		return remoteAddr
	}

	// RemoteAddr
	remoteAddr = req.RemoteAddr
	if remoteAddr != "" {
		lg.ILogger.Println("remoteAddr")
		remoteAddr = removePort(remoteAddr)
		return remoteAddr
	}
	// ipv4
	remoteAddr = req.Header.Get("ipv4")
	if remoteAddr != "" {
		lg.ILogger.Println("ipv4")
		return remoteAddr
	}
	//
	remoteAddr = req.Header.Get("XForwardedFor")
	if remoteAddr != "" {
		lg.ILogger.Println("XForwardedFor")
		return remoteAddr
	}
	// X-Forwarded-For
	remoteAddr = req.Header.Get("X-Forwarded-For")
	if remoteAddr != "" {
		lg.ILogger.Println("X-Forwarded-For")
		return remoteAddr
	}

	return remoteAddr
}
